package com.googlecode.bip.xml.export;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import javax.naming.NamingException;

/**
 * TODO: doc
 *
 * @author Claude CHOISNET
 */
public class XMLSurveyFactory
{
    /**
     * default DTD URL : "{@value}"
     */
    private final static String _DEFAULT_DTD_URL_ =
        "http://bipol.claude-cloudbees.cloudbees.net/schema/survey.dtd";

    /**
     * Export survey from MySQL data base.
     *
     * @param appender Append that will receive XML.
     * @param encoding XML encoding that will be produce by appender.
     *                 For example "iso-8859-1"
     * @param dtdSystemUrl
     * @throws IOException if any
     * @throws SQLException if any
     * @throws NamingException if any
     */
    public static void exportXML(
            final Appendable  appender,
            final String      encoding,
            final String      dtdSystemUrl
            ) // iso-8859-1
        throws IOException, SQLException, NamingException
    {
        XMLSurveyConnection connection = new XMLSurveyConnection();

        try {
            XMLSurvey survey = new XMLSurvey( connection );

            appender.append( "<?xml version=\"1.0\" encoding=\"").append( encoding ).append( "\" ?>\n" )
                    .append( "<!DOCTYPE survey SYSTEM \"").append( dtdSystemUrl ).append( "\">\n" );

            survey.appendXML( appender );
            }
        finally {
            connection.close(); // back to pool
            }
    }

    /**
     * Export survey from data base.
     * <br/>
     * Do export using {@link #export(Appendable, String, String)} providing
     * default DTD URL.
     *
     * @param appender Append that will receive XML.
     * @param encoding XML encoding that will be produce by appender.
     *                 For example "iso-8859-1"
     *
     * @throws IOException if any
     * @throws SQLException if any
     * @throws NamingException if any
     */
    public static void exportXML(
            final Appendable  appender,
            final String      encoding
            )
        throws IOException, SQLException, NamingException
    {
        exportXML( appender, encoding, getDefaultDTDSystemURLString() );
    }

    /**
     * Returns default DTD URL as a String
     * @return default DTD URL as a String
     */
    public static String getDefaultDTDSystemURLString()
    {
        return _DEFAULT_DTD_URL_;
    }

    /**
     * Returns default DTD URL
     * @return default DTD URL
     * @throws MalformedURLException if any
     */
    public static URL getDefaultDTDSystemURL()
        throws MalformedURLException
    {
        return new URL( getDefaultDTDSystemURLString() );
    }
}
